using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DatabaseManager.Filters;

public class AdminAuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var session = context.HttpContext.Session;
        var isAuthenticated = session.GetString("IsAuthenticated");
        
        if (isAuthenticated != "true")
        {
            // 如果是 API 请求，返回 401
            if (context.HttpContext.Request.Path.StartsWithSegments("/api"))
            {
                context.Result = new UnauthorizedResult();
            }
            else
            {
                // 如果是页面请求，重定向到登录页面
                context.Result = new RedirectToActionResult("Login", "Home", null);
            }
        }
        
        base.OnActionExecuting(context);
    }
}